package org.ysling.litemall.core.util.captcha;
// Copyright (c) [ysling] [927069313@qq.com]
// [litemall-plus] is licensed under Mulan PSL v2.
// You can use this software according to the terms and conditions of the Mulan PSL v2.
// You may obtain a copy of Mulan PSL v2 at:
//             http://license.coscl.org.cn/MulanPSL2
// THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
// EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
// MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
// See the Mulan PSL v2 for more details.

import java.time.LocalDateTime;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 缓存系统中的验证码
 */
public class CaptchaCodeManager {

    /**
     * 验证码存储map线程安全
     */
    private static ConcurrentHashMap<String, CaptchaItem> captchaCodeCache = new ConcurrentHashMap<>();
    /**
     * 默认过期时间  单位分钟
     */
    private static Integer DEFAULT_EXPIRE_TIME = 1;

    /**
     * 添加到缓存
     *
     * @param account     账号
     * @param code        验证码
     */
    public static boolean addToCache(String account, String code) {
        //已经发过验证码且验证码还未过期
        if (captchaCodeCache.get(account) != null) {
            if (captchaCodeCache.get(account).getExpireTime().isAfter(LocalDateTime.now())) {
                return false;
            } else {
                //存在但是已过期，删掉
                captchaCodeCache.remove(account);
            }
        }
        //创建验证码实体类
        CaptchaItem captchaItem = new CaptchaItem();
        captchaItem.setAccount(account);
        captchaItem.setCode(code);
        // 设置过期时间
        captchaItem.setExpireTime(LocalDateTime.now().plusMinutes(DEFAULT_EXPIRE_TIME));
        // 添加进map
        captchaCodeCache.put(account, captchaItem);
        return true;
    }

    /**
     * 获取缓存的验证码
     *
     * @param account   关联的账号
     * @return 验证码
     */
    public static String getCachedCaptcha(String account) {
        //没有这个电话记录
        if (captchaCodeCache.get(account) == null){
            return null;
        }

        //有电话记录但是已经过期
        if (captchaCodeCache.get(account).getExpireTime().isBefore(LocalDateTime.now())) {
            return null;
        }

        return captchaCodeCache.get(account).getCode();
    }
}
